﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SignalRService.Model
{
    public class OPUserCollection
    {
        static OPUserCollection instance;
        public static OPUserCollection shared
        {
            get
            {
                if (instance == null)
                    instance = new OPUserCollection();
                return instance;
            }
        }
        private readonly List<OPUser> Users = new List<OPUser>();
        private readonly List<OPIndexedUser> userlist = new List<OPIndexedUser>();
        public void AddUser(OPUser user)
        {
            lock(Users)
            {
                Users.Add(user);
            }
            lock(userlist)
            {
                OPIndexedUser u = new OPIndexedUser()
                {
                    userId = user.userId,
                    state = user.state
                };
                int index = userlist.FindIndex(k => k.userId == u.userId);
                if(index == -1)
                    userlist.Add(u);
            }
        }
        public void RemoveUser(OPUser user)
        {
            lock(Users)
            {
                user.Dispose();
                Users.Remove(user);
            }
        }
        public void RemoveConnection(string uid,string connection)
        {
            lock(Users)
            {
                OPUser user = OPUserCollection.shared.FindUser(u => u.userId == uid);
                if(user != null)
                {
                    lock(user.connections)
                    {
                        user.connections.Remove(connection);
                        if(user.connections.Count == 0)
                        {
                            Users.RemoveAll(u => u.userId == uid);
                        }
                    }
                }
            }
        }
        public OPIndexedUser FindIndexedUser(Predicate<OPIndexedUser> predicator)
        {
            return userlist.Find(predicator);
        }
        public OPUser FindUser(Predicate<OPUser> predicator)
        {
            return Users.Find(predicator);
        }
    }
}